package main

import (
    "net/http"
	"github.com/labstack/echo"
	"fmt"
	"encoding/json"
	"io"
	"bufio"
	"os"
	"time"
	"strings"
	"math/rand"
	"log"
	// "io/ioutil"
	// "net/url"
	
)
// 读取key=value类型的配置文件ini
func InitConfig(path string) map[string]string {
	config := make(map[string]string)

	f, err := os.Open(path)
	defer f.Close()
	if err != nil {
		panic(err)
	}

	r := bufio.NewReader(f)
	for {
		b, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}
		s := strings.TrimSpace(string(b))
		index := strings.Index(s, "=")
		if index < 0 {
			continue
		}
		key := strings.TrimSpace(s[:index])
		if len(key) == 0 {
			continue
		}
		value := strings.TrimSpace(s[index+1:])
		if len(value) == 0 {
			continue
		}
		config[key] = value
	}
	return config
}
// 获取随机字符串
func  GetRandomString(l int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyz"
	bytes := []byte(str)
	result := []byte{}
	result = append(result, 'b')
	result = append(result, 'x')
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}
func  CreateNoncestr(l int) string {
	str := "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}


var g_config map[string]string
var g_client *Client
func main() {
	
	logFile, err := os.OpenFile("./webapp.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println("open log file failed, err:", err)
		return
	}
	log.SetOutput(logFile)//设置输出位置
	log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)//设置输出格式



	g_config = InitConfig("config.ini")
	g_client = NewClient(g_config["AppId"], g_config["MchId"], g_config["ApiKey"])

	// 附着商户证书
	err = g_client.WithCert(g_config["CertFile"], g_config["KeyFile"], g_config["RootcaFile"])
	if err != nil {
		log.Fatal(err)
	}

    e := echo.New()
    e.GET("/", hello)
	e.POST("/bxpay", bxpay);
    e.Logger.Fatal(e.Start(":1323"))
}
func hello(c echo.Context) error {
	// return c.String(http.StatusOK, g_config["RootcaFile"])
	return c.String(http.StatusOK, CreateNoncestr(32))
}

type WithDraw struct {
	User_id  int `json:"user_id" xml:"user_id" form:"user_id" query:"user_id"`
	Openid  string `json:"openid" xml:"openid" form:"openid" query:"openid"`
	Partner_trade_no  string `json:"partner_trade_no" xml:"partner_trade_no" form:"partner_trade_no" query:"partner_trade_no"`
	Desc  string `json:"desc" xml:"desc" form:"desc" query:"desc"`
	Amount  int `json:"amount" xml:"amount" form:"amount" query:"amount"`
}

func bxpay(c echo.Context) error {

	wd := new(WithDraw)
	if err := c.Bind(wd); err != nil {
		log.Fatal(err)
		return err
	}
	wdStr, err := json.Marshal(wd)
    if err != nil {
        log.Fatal("生成json字符串错误")
	}
	fmt.Println("bxpay wdstr", string(wdStr))

	params := make(Params)
	// 查询企业付款接口请求参数
	params.SetString("appid", g_client.AppId)
	params.SetString("mch_id", g_client.MchId)
	params.SetString("nonce_str", CreateNoncestr(32))  // 随机字符串
	params.SetString("partner_trade_no", wd.Partner_trade_no) // 商户订单号
	params.SetString("openid", wd.Openid)
	params.SetString("check_name", "NO_CHECK")
	params.SetInt64("amount", int64(wd.Amount))
	params.SetString("desc", wd.Desc)
	params.SetString("sign", g_client.Sign(params)) // 签名

	url := "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"
	// 发送查询企业付款请求
	ret, err := g_client.Post(url, params, true)
	if err != nil {
		log.Print(err)
		return c.String(http.StatusInternalServerError, "请求失败")
	}

	log.Print(ret)
	str, err := json.Marshal(ret)
	if err != nil {
		log.Print(err)
		return c.String(http.StatusInternalServerError, "转换json失败")
	}
	log.Print(string(str))

	return c.JSON(http.StatusCreated, string(str))
	
}